﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Output;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;

namespace MesProjectWinform.Public.Form
{
    public partial class UserLoginForm : DevExpress.XtraEditors.XtraForm
    {
        public UserLoginForm()
        {
            InitializeComponent();

            // 设置按Enter键登录
            this.AcceptButton = simpleButton1;

            // 设置初始焦点为用户名输入框
            this.ActiveControl = UserName;
        }
        /// <summary>
        /// 登录按钮点击事件
        /// </summary>
        /// <param name="sender">事件源对象</param>
        /// <param name="e">事件参数</param>
        private async void UserLoginButton1_Click(object sender, EventArgs e)
        {
            // 获取用户名和密码输入框的内容，并去除首尾空格
            var userName = UserName.Text.Trim();
            var password = Password.Text.Trim();

            // 输入验证：用户名或密码为空时，弹出警告提示
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                XtraMessageBox.Show("用户名和密码不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 显示等待光标，禁用登录按钮，修改按钮文本为“登录中...”
                this.Cursor = Cursors.WaitCursor;
                simpleButton1.Enabled = false;
                simpleButton1.Text = "登录中...";

                // 创建HttpClient实例，用于发送HTTP请求
                using (var cilent = new HttpClient())
                {
                    //password = PasswordHelper.AesEncrypt(password);
                    // 构造登录参数对象
                    var loginData = new UserLoginOutput
                    {
                        UserName = userName,
                        Password = password
                    };

                    // 将登录参数序列化为JSON字符串
                    var json = JsonConvert.SerializeObject(loginData);
                    // 构造HTTP请求内容，设置内容类型为application/json
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送POST请求到登录API（请根据实际API地址调整）
                    var response = await cilent.PostAsync("http://47.110.243.157:5239/api/User/UserLogin", content);

                    // 判断HTTP响应是否成功
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        var responseContent = await response.Content.ReadAsStringAsync();
                        // 反序列化为ApiResult<UserLoginOutput>对象
                        var result = JsonConvert.DeserializeObject<ApiResult<UserLoginOutput>>(responseContent);
                        if (result != null)
                        {
                            // 判断API返回的状态码是否为成功
                            if (result.Code == ApiEnums.Success)
                            {
                                RequestUser.CurrentUser = result.Data;
                                // 登录成功，弹出提示并跳转到主页面
                                //XtraMessageBox.Show("登录成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                MainForm mainForm = new MainForm();
                                mainForm.Show();
                                this.Hide();
                            }
                            else
                            {
                                // 登录失败，弹出错误提示
                                string errorMessage = result != null ? result.Message : "未知错误";
                                XtraMessageBox.Show($"登录失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常，弹出错误提示
                XtraMessageBox.Show($"登录过程中发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标和按钮状态
                this.Cursor = Cursors.Default;
                simpleButton1.Enabled = true;
                simpleButton1.Text = "登录";
            }
        }

        private void UserLoginForm_Load(object sender, EventArgs e)
        {

        }
    }
}